from flask import session, escape, current_app, jsonify, request
import qrcode
import uuid
import os


def get_user_id():
    if 'uid' in session:
        user_id = escape(session['uid'])
        return user_id
    else:
        return None


def get_qr_code(code_content, file_name, code_box_size=10, code_border=1, code_version=1,
                   code_error_correction=qrcode.constants.ERROR_CORRECT_L):
    qr = qrcode.QRCode(
        version=code_version,
        error_correction=code_error_correction,
        box_size=code_box_size,
        border=code_border,
    )

    qr.add_data(code_content)
    qr.make(fit=True)

    img_object = qr.make_image()
    filename = file_name + '.jpg'
    savepath = current_app.config.get('LOGIN_QR_PATH') + filename
    if not os.path.exists(current_app.config.get('LOGIN_QR_PATH')):
        os.mkdir(current_app.config.get('LOGIN_QR_PATH'))
    img_object.save(savepath)

    return '/qrcode/'+filename


def get_post_data(key):
    post_data = request.get_json()
    if key in post_data:
        return post_data[key]
    else:
        return None


def set_response(code, msg, data):
    return jsonify({
        'state': code,
        'msg': msg,
        'data': data
    })
